package com.android.fragmentdemo.thread16

import org.junit.Test
import java.util.concurrent.locks.ReentrantLock

class Demo16 {
    @Test
    fun testRunnable() {
        val account = Account("123456", 10000.00)
        val thread1 = DrawThread("th1", account, 3000.0)
        val thread2 = DrawThread("th2", account, 2000.0)
        val thread3 = DrawThread("th3", account, 4000.0)
        thread1.start()
        thread2.start()
        thread3.start()

        Thread.sleep(5 * 1000)
    }

    class DrawThread(threadName: String, accountNo: Account, amountMoney: Double) : Thread(threadName) {
        private val mAccountNo = accountNo
        private val mAmountMoney = amountMoney
        override fun run() {
            super.run()
            mAccountNo.draw(mAmountMoney)
        }
    }

    data class Account(var accountNo: String, var balance: Double) {
        private val mLock = ReentrantLock()
        fun draw(amountCount: Double) {
            mLock.lock()
            try {
                if (balance >= amountCount) {
                    println("${Thread.currentThread().name}从账户${accountNo}取出金额:${amountCount}")
                    balance -= amountCount
                    println("账户${accountNo}剩余金额:${balance}")
                } else {
                    println("账户${accountNo}剩余金额不足")
                }
            } finally {
                mLock.unlock()
            }
        }
    }

}